import fly from '@/utils/fly'
import { api } from '@/api/login'
import { SET_TOKEN, SET_NAME } from '@/store/mutations-type'

const user = {
  state: {
    token: '',
    userInfo: {
      id:undefined,
      username: undefined,
      tureNameAuth: false
    },
    isLogin: false
  },
  mutations: {
    SET_USER_INFO(state, data) {
      state.userInfo = data
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_TRUENAME_AUTH: (state, tureNameAuth) => {
      state.userInfo.tureNameAuth = tureNameAuth
    },
    SET_ISLOGIN(state, isLogin) {
      state.isLogin = isLogin
    }

  },
  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      userInfo.username = username
      return new Promise((resolve, reject) => {
        api
          .login(userInfo)
          .then(response => {
            const token = response.data
            wx.setStorageSync('sessionToken', token)
            wx.setStorageSync('isLogin', true)
            // setToken(token)
            // commit('SET_TOKEN', token)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetWorkerInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        api
          .getWorkerInfo(wx.getStorageSync('sessionToken'))
          .then(response => {
            const data = response.data
            wx.setStorageSync('userInfo', data)
            // commit('SET_NAME', data.name)
             resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        api
          .logout(state.token)
          .then(() => {
            wx.setStorageSync('sessionToken', null)
            wx.setStorageSync('userInfo', null)
            wx.setStorageSync('isLogin', false)
            wx.reLaunch({url:'../index2/index'})
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        // commit('SET_TOKEN', '')
        // removeToken()
        wx.setStorageSync('sessionToken', null)
        wx.setStorageSync('userInfo', null)
      })
    }
  }
}

export default user
